const { fetchData } = require('./utils/fetchRecom');
const { fetchDetail } = require('./utils/fetchDetail');
const { aiHelper } = require('./utils/aiHelper')

const fs = require('fs')

function writeToTxtFile(data, filePath) {
    const content = JSON.stringify(data, null, 2)

    fs.writeFileSync(filePath, content);
}


const genFinal = () => {
    const fs = require('fs');
    const path = require('path');

    const jsonFiles = [];


    // 读取 data 文件夹中的所有文件
    fs.readdirSync(path.join(__dirname, 'data')).forEach(file => {
        // 检查文件是否为 JSON 文件
        if (path.extname(file) === '.json') {
            // 读取 JSON 文件内容并解析为对象
            const jsonData = JSON.parse(fs.readFileSync(path.join(__dirname, 'data', file), 'utf8'));
            jsonFiles.push(jsonData);
        }
    });

    const writeData = jsonFiles.sort((a, b) => a.createTime - b.ccreateTime)

    writeToTxtFile(writeData, './final.json')

    // 现在 jsonFiles 数组包含了所有 JSON 文件的内容
    // console.log(jsonFiles);
}
const init = async () => {
    const data = await fetchData()

    console.log(data)

    for (let item of data) {
        const id = item.id
        const display_title = item.note_card.display_title
        const xsec_token = item.xsec_token

        const desc = await fetchDetail(id, xsec_token)
        createTime = Date.now()
        const obj = {
            id, display_title, xsec_token, desc, createTime
        }

        const aiResult = await aiHelper(JSON.stringify(obj))

        obj.aiResult = aiResult
        writeToTxtFile(obj, `./data/${item.id}.json`)
    }
}


const main = async () => {
    try {
        await init()
        await new Promise(resolve => setTimeout(resolve, 10 * 1000))
        genFinal()
        await new Promise(resolve => setTimeout(resolve, 10 * 1000))
    } catch (err) {
        console.log(err)
    }
    console.log("main done")
}


module.exports = {
    main
};